<!-- eslint-disable vue/html-indent -->
<template>
  <view class="mgt1" v-if="data.setList.length > 0">
    <tm-sheet
      :margin="[0]"
      :padding="[32, 20]"
      v-for="(item, index) in data.setList.filter(tagFilter)"
      :key="index"
    >
      <directory-main
        :key="item.id"
        :content="item"
        :index="index"
        :isShowRight="data.topLevel ? true : false"
        :isSelectMode="false"
        :enableTouch="false"
        @btnClick="clickFile"
      ></directory-main>
    </tm-sheet>
  </view>

  <tm-sheet v-else :margin="[0]">
    <tm-result :showBtn="false" subTitle=" " title="暂无数据"></tm-result>
  </tm-sheet>
</template>

<script lang="ts" setup>
import { IFile } from '@/ts/core'
import { ref, reactive, watch } from 'vue'
import orgCtrl from '@/ts/controller'
import directoryMain from '@/components/Directory/main.vue'

type dataTypes = {
  setList: IFile[] | []
  topLevel: boolean
}
type Props = {
  updateFlag: boolean
}
const props = defineProps<Props>()
watch(
  () => props.updateFlag,
  newValue => {
    //触发进来
    if (newValue) {
      getList()
    } else {
      data.setList = []
      data.topLevel = true
    }
  }
)
const isUpdating = ref(false)
const data = reactive<dataTypes>({
  setList: [],
  topLevel: true
})
const emit = defineEmits(['updateFile'])
const clickFile = async (
  file: IFile | undefined,
  _index: number,
  type?: string
) => {
  if (isUpdating.value) return // 检查标志
  isUpdating.value = true // 设置为正在更新
  uni.showLoading({ title: '加载中...' })
  // 防止重复设置焦点
  if (file && file.key) {
    if (type == 'disk') {
      if ('isContainer' in file && file.isContainer && !data.topLevel) {
        try {
          file?.loadContent(false).then(() => {
            data.setList = file.content()
          })
        } catch (error) {
          console.error('加载内容失败', error)
        }
      } else {
        try {
          await file.directory.loadContent(false) // 加载内容
          data.setList = file.directory.content()
        } catch (error) {
          console.error('加载内容失败', error)
        }
        data.topLevel = false
      }
    }
    if (type == 'colony') {
      data.setList = file.content()
      data.topLevel = true
    }
  }
  uni.hideLoading()
  isUpdating.value = false // 更新结束
  emit('updateFile', file)
}
const getList = async () => {
  uni.showLoading({ title: '加载中...' })
  await orgCtrl.user.loadTeams()
  data.setList = [orgCtrl.user, ...orgCtrl.user.companys]
  uni.hideLoading()
}
const tagFilter = (file: IFile) => {
  return !file.filterTags.includes('已删除')
}
</script>

<style lang="scss">
@import '../../common/style/global.scss';
</style>
@/ts/core